import SwiftUI

struct FeedView: View {
    @StateObject var viewModel = MainPicaViewModel()
    @State var videos_test: [MainPica] = mainpicas
    @State private var scrollPosition: Int?
    @State var item: MainPica = mainpicas[1]
    @State private var hasAppeared = false
    @State private var currentPage: Int = 1
    @State private var isLoading = false // 用于防止重复加载
    @StateObject private var playbackManager = VideoPlaybackManager.shared
    
    var body: some View {
        
        ScrollView {
            LazyVStack(spacing: 0) {
                ForEach(viewModel.video_list) { video in
                    FeedCell(post: video)
                        .id(video.id)
                }
            }
            .scrollTargetLayout()
        }
        .scrollIndicators(.hidden) // 隐藏滚动条
        .onAppear{
            if !hasAppeared {
                // 执行首次加载的代码
                viewModel.get_videos(type: item.type, page: currentPage,video_id: item.id)
                hasAppeared = true
                
                // 设置初始播放的视频（第一个视频）
                if let firstVideo = viewModel.video_list.first {
                    print("🎬 初始化播放第一个视频: \(firstVideo.id)")
                    playbackManager.startPlaying(videoId: String(firstVideo.id))
                }
            }
        }
        .scrollPosition(id: $scrollPosition)
        .scrollTargetBehavior(.paging)
        .ignoresSafeArea()
        .onChange(of: scrollPosition) { oldValue, newValue in
            print("最新的视频id\(newValue ?? 0)")
            
            // 当滚动位置改变时，更新当前播放的视频
            if let newVideoId = newValue {
                // 先停止当前播放的视频
                if let oldVideoId = oldValue {
                    print("⏸️ 停止播放视频: \(oldVideoId)")
                }
                
                // 开始播放新的视频
                print("🎬 FeedView滑动，开始播放视频: \(newVideoId)")
                playbackManager.startPlaying(videoId: String(newVideoId))
                
                // 预加载下一个视频
                preloadNextVideo(currentIndex: newVideoId)
            } else {
                // 如果没有选中的视频，暂停所有视频
                print("⏸️ 没有选中的视频，暂停所有视频")
                playbackManager.pauseAllVideos()
            }
            
            if newValue == viewModel.video_list.last?.id {
                loadNextPage()
            }
        }
        .background(.black)
        .navigationBarBackButtonHidden()
        
    }
    
    
    
    private func loadNextPage() {
        isLoading = viewModel.isLoading
        if !isLoading {
            triggerHapticFeedback()
            print("加载下一页: 当前页数 \(currentPage)")
            currentPage += 1
            viewModel.get_videos(type: item.type, page: currentPage,video_id: item.id)
            
        }
    }
    
    // 预加载下一个视频
    private func preloadNextVideo(currentIndex: Int) {
        // 找到当前视频在列表中的索引
        if let currentVideoIndex = viewModel.video_list.firstIndex(where: { $0.id == currentIndex }) {
            let nextIndex = currentVideoIndex + 1
            if nextIndex < viewModel.video_list.count {
                let nextVideo = viewModel.video_list[nextIndex]
                playbackManager.setPreloadVideo(videoId: String(nextVideo.id))
                
                // 缓存功能已禁用
                
                print("🔄 预加载下一个视频: \(nextVideo.id)")
            } else {
                // 没有下一个视频，清除预加载
                playbackManager.setPreloadVideo(videoId: nil)
            }
        }
    }
    
}

#Preview {
    FeedView()
}
